package Pet.Management.repository;

import Pet.Management.domain.entity.Message;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
    // 基本查询方法
    Page<Message> findByReceiverId(Long receiverId, Pageable pageable);
    Page<Message> findBySenderId(Long senderId, Pageable pageable);
    Page<Message> findByType(String type, Pageable pageable);
    Page<Message> findByReceiverIdAndType(Long receiverId, String type, Pageable pageable);
    
    // 按多类型查询
    @Query("SELECT m FROM Message m WHERE m.receiverId = :userId AND m.type IN :types ORDER BY m.createTime DESC")
    Page<Message> findByReceiverIdAndTypeIn(@Param("userId") Long userId, @Param("types") List<String> types, Pageable pageable);
    
    // 计数方法
    long countByReceiverIdAndIsRead(Long receiverId, Boolean isRead);
    long countByReceiverIdAndTypeAndIsRead(Long receiverId, String type, Boolean isRead);
    
    // 高级查询方法
    @Query("SELECT m FROM Message m WHERE (m.type = 'system') OR (m.receiverId = :userId) ORDER BY m.createTime DESC")
    Page<Message> findUserMessagesAndAnnouncements(@Param("userId") Long userId, Pageable pageable);
    
    @Query("SELECT m FROM Message m WHERE (m.senderId = :userId AND m.receiverId = :otherUserId) OR (m.senderId = :otherUserId AND m.receiverId = :userId) ORDER BY m.createTime ASC")
    List<Message> findConversation(@Param("userId") Long userId, @Param("otherUserId") Long otherUserId);
    
    // 管理员查询
    Page<Message> findByTypeAndStatus(String type, String status, Pageable pageable);
    Page<Message> findByTypeAndTitleContaining(String type, String title, Pageable pageable);
    Page<Message> findByTypeAndStatusAndTitleContaining(String type, String status, String title, Pageable pageable);
    
    // 批量操作
    @Modifying
    @Transactional
    @Query("UPDATE Message m SET m.isRead = true WHERE m.id = :messageId AND m.receiverId = :userId")
    void markAsRead(@Param("messageId") Long messageId, @Param("userId") Long userId);
    
    @Modifying
    @Transactional
    @Query("UPDATE Message m SET m.isRead = true WHERE m.receiverId = :userId")
    void markAllAsRead(@Param("userId") Long userId);
} 